/***************************************************
> Copyright (C) 2024 ==KINGYI== All rights reserved.
> File Name: 1.c
> Author:cjy
> Mail: 
> Created Time: 2024年08月09日 星期5 11时14分25秒
***************************************************/
// 将当前队列中的元素个数通过共享内存传递给监控进程
#include "queue.h"
#include "shmget.h"

int flag = 1;
typedef struct content{
	sem_t semr;
	sem_t semw;
	pthread_mutex_t mutex;
	struct queue *que;
}CON;

void fun(int sig){
	flag = 0;	
	printf("guanbichenggong\n");
}

void *fun1(void *arg)
{	
	int dat = 0;
	CON *p = (CON *)arg;
	while(flag == 1)
	{	
		sem_wait(&p->semw);
		if(flag == 0){
			break;		
		}	
		pthread_mutex_lock(&p->mutex);
	
		dat++;
		push(dat,p->que);

		sem_post(&p->semr);

		pthread_mutex_unlock(&p->mutex);
	}
}

void *fun2(void *arg)
{
	int dat = 0;
	CON *p = (CON *)arg;
	while(flag == 1)
	{
		sem_wait(&p->semr);
		if(flag == 0){
			break;		
		}
		pthread_mutex_lock(&p->mutex);

		dat = front(p->que);
		pop(p->que);
		printf("dat = %d\n",dat);
		printf("size = %d\n",size(p->que));

		sem_post(&p->semw);

		pthread_mutex_unlock(&p->mutex);
		sleep(1);
	}
}

int main()
{
	printf("%d\n",getpid());
	pthread_t tid1 = 0,tid2 = 0;
	int ret = 0;
	CON sem;
	
	sem.que = create_queue();	
	sem_init(&sem.semw,0,10);
	sem_init(&sem.semr,0,0);
	pthread_mutex_init(&sem.mutex,NULL);


	ret = pthread_create(&tid1,NULL,fun1,&sem);
	if(ret != 0)
	{
		perror("pthread_create");
		exit(-1);
	}

	ret = pthread_create(&tid2,NULL,fun2,&sem);
	if(ret != 0)
	{
		perror("pthread_create");
		exit(-1);
	}
	signal(SIGINT,fun);
	
	int *p = create_mem(1024);
	
	
	while(1){
		printf("%d",flag);
		if(flag == 0){
				break;		
			}
		sleep(1);
		*p = size(sem.que);
	}
	sem_post(&sem.semw);
	sem_post(&sem.semr);
	
	if (isempty(sem.que) != 0){
		delLinkMem(sem.que);
	}
	printf("lianbiaokong\n");	

	pthread_join(tid1,NULL);
	pthread_join(tid2,NULL);

	sem_destroy(&sem.semr);
	sem_destroy(&sem.semw);
	
	pthread_mutex_destroy(&sem.mutex);

	return 0;

}







